package com.czk.springcloud.ownFeign.register;

import com.czk.springcloud.ownFeign.annotation.MyFeign;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.client.RestTemplate;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @Author:ChenZhangKun
 * @Date: 2021/5/13 15:23
 */
public class MyFactoryBean implements FactoryBean {
    @Autowired
    private RestTemplate restTemplate;

    @Override
    public Object getObject() throws Exception {
        // 拿到上下文加载器
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        // 擦黄建数组
        Class[] classes = {MyFeignService.class};
        MyFeign myFeign = MyFeignService.class.getAnnotation(MyFeign.class);
        String value = myFeign.value();
        return Proxy.newProxyInstance(classLoader, classes, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                String path = "";
                if (method.isAnnotationPresent(GetMapping.class)) {
                    // 拿到path
                    String s = method.getAnnotation(GetMapping.class).value()[0];
                    // 替换{}
                    s = s.replaceAll("\\{id}", args[0] + "");
                    // 返回执行结果
                    return restTemplate.getForObject("http://" + value + s, method.getReturnType(), args[0]);
                }
                return null;
            }
        });
    }

    @Override
    public Class<?> getObjectType() {
        return MyFeignService.class;
    }

    @Override
    public boolean isSingleton() {
        return true;
    }
}
